# core/report_analyzer.py
import json
import os
import subprocess
from datetime import datetime
from typing import Dict, Optional
from config.settings import Settings
from utils.file_utils import save_file
from utils.str_utils import extract_json_from_markdown, extract_html_from_markdown
from .aigc_integration import CozeAssistant, DEEPSEEKAssistant, DashscopeAssistant


class SmartReportAnalyzer:
    def __init__(self, coze_assistant: Optional[CozeAssistant] = None,
                 deepseek_assistant: Optional[DEEPSEEKAssistant] = None,
                 dashscope_assistant: Optional[DashscopeAssistant] = None):
        # 根据配置选择使用哪个助手
        self.aigc_provider = Settings.AIGC_PROVIDER.lower()

        if self.aigc_provider == "coze":
            self.assistant = coze_assistant or CozeAssistant()
            self.assistant_name = "COZE"
        elif self.aigc_provider == "deepseek":
            self.assistant = deepseek_assistant or DEEPSEEKAssistant()
            self.assistant_name = "DEEPSEEK"
        elif self.aigc_provider == "dashscope":
            self.assistant = dashscope_assistant or DashscopeAssistant()
            self.assistant_name = "Aliyun-百炼"
        else:
            raise ValueError(f"Unsupported AIGC provider: {Settings.AIGC_PROVIDER}")

    def analyze_report(self, report_path: str) -> dict:
        """分析测试报告并提供改进建议"""
        try:
            with open(report_path, 'r') as f:
                report = json.load(f)
        except FileNotFoundError:
            print(f"❌ 报告文件未找到: {report_path}")
            return {}
        except json.JSONDecodeError:
            print(f"❌ 报告文件格式错误: {report_path}")
            return {}

        summary = report.get("summary", {})
        passed = summary.get('passed', 0)
        failed = summary.get('failed', 0)
        total = summary.get('total', passed + failed)
        pass_rate = (passed / total * 100) if total > 0 else 0

        prompt = f"""
        作为首席质量保障专家，请分析以下测试报告:

        === 测试摘要 ===
        总测试数: {total}
        通过数: {passed} ({pass_rate:.1f}%)
        失败数: {failed}
        执行时间: {summary.get('duration', 0):.2f}秒
        收集时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}

        === 分析要求 ===
        请提供:
        1. 质量评估报告 (包括总体质量评分)
        2. 高风险区域分析 (列出高风险功能模块)
        3. 测试覆盖率改进建议 (具体模块和建议)
        4. 测试效率优化建议 (如测试用例重复、执行时间优化等)
        5. 后续测试重点 (优先级排序)

        返回JSON格式:
        {{
            "quality_assessment": {{
                "score": 0-100,
                "summary": "总体质量评估摘要"
            }},
            "high_risk_areas": [
                {{"module": "模块名称", "risk_level": "高/中/低", "description": "风险描述"}}
            ],
            "coverage_suggestions": [
                {{"module": "模块名称", "suggestion": "改进建议"}}
            ],
            "efficiency_improvements": [
                {{"area": "改进领域", "suggestion": "具体建议"}}
            ],
            "testing_focus": [
                {{"priority": 1, "area": "重点测试区域", "reason": "原因说明"}}
            ]
        }}
        """
        # 使用统一的接口调用
        response = self.assistant.generate(prompt, max_tokens=3000)
        # print(response)
        # 首先提取 JSON 内容
        json_content = extract_json_from_markdown(response.strip())
        # print(json_content)
        try:
            analysis = json.loads(json_content.strip())
            print("✅ 测试报告分析完成")
            return analysis
        except json.JSONDecodeError:
            print("❌ 解析分析结果JSON失败")
            return {}

    def generate_visual_report(self, analysis: dict, report_data: Optional[dict] = None) -> str:
        """生成可视化报告"""
        if not analysis:
            return "<html><body>无分析数据</body></html>"

        prompt = f"""
        根据以下分析结果，生成HTML格式的可视化报告:
        {json.dumps(analysis, indent=2)}

        {f'测试数据: {json.dumps(report_data, indent=2)}' if report_data else ''}

        要求:
        1. 报告的标题为：基于 {self.assistant_name} 的软件测试质量分析报告
        2. 添加页脚包含生成日期,日期为当前系统时间，格式为"YYYY-MM-DD HH:mm:ss"

        返回完整的HTML:
        """
        # 使用统一的接口调用
        html_report = self.assistant.generate(prompt, max_tokens=4000)
        return html_report

    def save_visual_report(self, analysis: dict, report_data: Optional[dict] = None,
                           file_path: Optional[str] = None) -> str:
        """生成并保存可视化报告"""
        html = self.generate_visual_report(analysis, report_data)
        # 首先提取 HTML 内容
        html_content = extract_html_from_markdown(html.strip())
        file_path = file_path or Settings.FINAL_REPORT_FILE
        save_file(file_path, html_content)
        print(f"✅ 可视化报告已保存: {file_path}")
        return file_path
